package com.wjw.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class AirCondition{

    public int i = 0;

    public Lock lock = new ReentrantLock();

    public Condition condition = lock.newCondition();

    public void increase(){

        lock.lock();
        try {
            if(i != 0){
                //this.wait();
                condition.await();
            }
            i++;
            System.out.println(Thread.currentThread().getName()+ ","+i);
            //this.notifyAll();
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  void reduce(){
        lock.lock();
        try{
            if(i == 0){
                //this.wait();
                condition.await();
            }
            i--;
            System.out.println(Thread.currentThread().getName()+ ","+i);
            //this.notifyAll();
            condition.signalAll();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
public class LockDemo1 {

    public static void main(String[] args) throws InterruptedException {

        AirCondition condition = new AirCondition();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("A----------i=" + i);
                condition.increase();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("B----------i=" + i);
                condition.reduce();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("C----------i=" + i);
                condition.increase();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("D----------i=" + i);
                condition.reduce();
            }
        },"D").start();
    }
}
